package algorithm;

import java.util.Stack;

/**
 * 232. 用栈实现队列
 */
public class T00232 {
    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.push(1);
        queue.push(2);
        System.out.println(queue.peek());  // 返回 1
        System.out.println(queue.pop());   // 返回 1
        System.out.println(queue.empty()); // 返回 false
    }

private static class MyQueue {
    private final Stack<Integer> stack;
    private final Stack<Integer> swap;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack = new Stack<>();
        swap = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stack.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        transfer();
        return swap.pop();
    }

    private void transfer() {
        if(swap.isEmpty()) {
            while (!stack.isEmpty()) // 转移到swap栈中
                swap.push(stack.pop());
        }
    }

    /** Get the front element. */
    public int peek() {
        transfer();
        return swap.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack.isEmpty() && swap.isEmpty();
    }
}
}